class Solution {
    typedef pair<int, int> PII;

    bool vis[51][51];
    int dx[4] = { 0, 0, -1, 1 };
    int dy[4] = { 1, -1, 0, 0 };
public:
    int maxAreaOfIsland(vector<vector<int>>& grid) {
        int m = grid.size(), n = grid[0].size();

        int ret = 0;
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (grid[i][j] == 1 && !vis[i][j])
                {
                    int s = bfs(grid, i, j);
                    ret = max(ret, s);
                }
            }
        }

        return ret;
    }

    int bfs(vector<vector<int>>& grid, int i, int j)
    {
        queue<PII> q;
        q.push({ i, j });
        vis[i][j] = true;

        int ret = 1;
        while (q.size())
        {
            auto [a, b] = q.front();
            q.pop();
            for (int k = 0; k < 4; k++)
            {
                int x = dx[k] + a;
                int y = dy[k] + b;
                if (x >= 0 && x < grid.size() && y >= 0 && y < grid[0].size() && grid[x][y] == 1 && !vis[x][y])
                {
                    ret++;
                    q.push({ x, y });
                    vis[x][y] = true;
                }
            }
        }

        return ret;
    }
};